package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Address;
import com.itheima.pojo.AddressName;
import com.itheima.service.AddressService;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * @program: myitcast_health
 * @ClassName: AddressController
 * @description:
 * @author: xiechangyu
 * @create: 2020-08-27 21:01
 **/
@RestController
@RequestMapping("/address")
public class AddressController {

    @Reference
    private AddressService addressService;

    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        PageInfo<Address> info = addressService.findPage(queryPageBean);
        return new PageResult(info.getTotal(), info.getList());
    }

    @RequestMapping("/addAddress")
    public Result addAddress(@RequestBody AddressName address) throws UnsupportedEncodingException {

        String addressName = address.getAddress();
        boolean flag = addressService.ifExist(addressName);

        if (flag) {
            try {
                addressService.addAddress(addressName);
                return new Result(true, MessageConstant.ADD_ADDRESS_SUCCESS);
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(false, MessageConstant.ADD_ADDRESS_FAIL);
            }
        } else {
            return new Result(false, MessageConstant.ADDRESS_HAS_EXIST);
        }


    }

    @RequestMapping("/deleteAddress")
    public Result deleteAddress(int id) {
        try {
            addressService.deleteAddress(id);
            return new Result(true, MessageConstant.DELETE_ADDRESS_SUSSESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.DELETE_ADDRESS_FAIL);
        }
    }

    @RequestMapping("/findAllAddress")
    public Result findAllAddress() {
        List<String> list = addressService.findAllAddress();
        System.out.println(list);
        return new Result(true, MessageConstant.QUERY_ADDRESS_SUCCESS, list);
    }

    @RequestMapping("/ifExist")
    public Result countByName(String addressName) {
        boolean b = addressService.ifExist(addressName);
        if (b == true) {
            return new Result(false, MessageConstant.ADDRESS_HAS_EXIST);
        }
        return new Result(true, MessageConstant.QUERY_ADDRESS_SUCCESS);
    }
}
